//
//  LZYDownLoaderView.m
//  Supervisor
//
//  Created by 小宇 on 2017/5/19.
//  Copyright © 2017年 北京怀教网络科技股份有限公司. All rights reserved.
//

#import "LZYDownLoaderView.h"
#import "LZYDownLoader.h"
#import "LZYDownLoadCell.h"
#import "LZYDownloaderManager.h"
#import "DownLoadModel.h"
@interface LZYDownLoaderView ()<UITableViewDelegate,UITableViewDataSource,UIDocumentInteractionControllerDelegate>
@property (nonatomic,strong)NSMutableArray *filesList;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic, copy) LZYDownLoaderViewFilesBlock downloadblock;
@property (nonatomic, strong) UIDocumentInteractionController *documentController;
@property (nonatomic, assign) BOOL hideDeleteButton;
@end

@implementation LZYDownLoaderView

- (instancetype)initWithFrame:(CGRect)frame FilesList:(NSArray *)filesList HideDeleteButton:(BOOL)hideDeleteButton{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self _setupWithFrame:frame FilesList:(NSArray *)filesList HideDeleteButton:hideDeleteButton];
    }
    return self;
}

//创建tableView用以显示文件视图
- (void)_setupWithFrame:(CGRect)frame FilesList:(NSArray *)filesList HideDeleteButton:(BOOL)hideDeleteButton{
    self.filesList = [NSMutableArray arrayWithArray:filesList];
    self.tableView = [[UITableView alloc]initWithFrame:frame];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.userInteractionEnabled = YES;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.hideDeleteButton = hideDeleteButton;
    [self addSubview:self.tableView];
}

# pragma mark --- tableviewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.filesList.count;
}

# pragma mark --- tableviewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LZYDownLoadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"LZYDownLoadCell" owner:self options:nil][0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.deleteBtn.hidden = self.hideDeleteButton;
    LZYWeakSelf(self)
    cell.deleteBlock = ^(id tabelCell) {//点击删除
        [self.filesList removeObjectAtIndex:indexPath.row];
        weakself.tableView.height = self.tableView.frame.size.height  - 55;
        weakself.block(weakself.tableView.height);
        [weakself.tableView reloadData];
    };
    cell.fileTitleLabel.text = self.filesList[indexPath.row][@"filename"];
    cell.fileSizeLabel.text = [NSString stringWithFormat:@"%@",[self.filesList[indexPath.row][@"filesize"] integerValue] < 1024 ? [NSString stringWithFormat:@"%@KB",self.filesList[indexPath.row][@"filesize"]] : [NSString stringWithFormat:@"%.0ldM",[self.filesList[indexPath.row][@"filesize"] integerValue]/1024]];
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}

//点击下载或查看
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSURL *fileUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",DigitalCampus_FileUrl,self.filesList[indexPath.row][@"filepath"]]];
    
    if ([LZYDownLoader cachePathWithURL:fileUrl]) {
        NSURL *cachePath = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@",[kPathCache stringByAppendingPathComponent:fileUrl.lastPathComponent]]];
        self.documentController =[UIDocumentInteractionController interactionControllerWithURL:cachePath];
        self.documentController.delegate = self;
        [self.documentController presentOptionsMenuFromRect:self.superview.bounds inView:self.superview animated:YES];
    }else{
        LZYWeakSelf(self)
        [[LZYDownloaderManager shareInstance]downLoadWithURL:fileUrl fileInfo:^(long long totalFileSize) {
            
        } success:^(NSString *cachePath, long long totalFileSize) {
            [SVProgressHUD dismiss];
            [LZYShowMsg showText:@"下载完成"];
            DownLoadModel *downLoadModel = [[DownLoadModel alloc]init];
            downLoadModel.cachePath = [kPathCache stringByAppendingPathComponent:cachePath.lastPathComponent];
            downLoadModel.titleName = weakself.filesList[indexPath.row][@"filename"];
            downLoadModel.byName = @"";
            downLoadModel.upLoadTime = [weakself.filesList[indexPath.row][@"createTime"] substringToIndex:16];
            downLoadModel.downloadId = weakself.filesList[indexPath.row][@"id"];
            [LZYModelOperationTool saveModel:downLoadModel withUserID:[[User shareInstance] getUserId]];
            self.documentController =[UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:downLoadModel.cachePath]];
            self.documentController.delegate = self;
            [self.documentController presentOptionsMenuFromRect:self.superview.bounds inView:self.superview animated:YES];
        } fail:^(NSString *errorMsg) {
            [LZYShowMsg showText:@"下载失败"];
        } progress:^(float progress) {
            [SVProgressHUD showProgress:progress status:@"下载中，请等待..."];
        } state:^(LZYDownLoaderState state) {
            
        }];
    }
}

- (void)setHideDeletebutton{
    self.hideDeleteButton = YES;
    [self.tableView reloadData];
}

- (void)setShowDeletebutton{
    self.hideDeleteButton = NO;
    [self.tableView reloadData];
}

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return [Tool getCurrentVC];
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
    return self.superview;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
    return  self.superview.frame;
}



//获取文件，用于上传
-(void)getDownLoadFileBlock:(LZYDownLoaderViewFilesBlock)filesBlock{
    _downloadblock = filesBlock;
    _downloadblock(self.filesList);
}

@end
